// components/sku-component/sku-component.js
import computedBehavior from 'miniprogram-computed'
Component({
  behaviors: [computedBehavior],
  /**
   * 组件的属性列表
   */
  properties: {
    show: { // 属性名
      type: Boolean,
      value: false
    },
    productSkuData: {
      type: Object,
      value: null
    },
    defaultNum: {
      type: Number,
      value: 1
    },
    defaultSkuVid: {
      type: String,
      value: ''
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    showDialog: false,
    img_url: '',
    price: '',
    product: {},
    sku: {},
    skuList: [],
    num: 1,
    stockKeys: []
  },

  watch: {
    'show'(newVal) {
      console.log('watch show', newVal)
      if (newVal) {
        let {
          product,
          sku
        } = this.data.productSkuData
        let skuList = [],
          skuID = '',
          stockKeys = Reflect.ownKeys(sku.sku_stock_map),
          defaultVidsList = []
        if (this.data.defaultSkuVid) {
          defaultVidsList = this.data.defaultSkuVid.split(',')
        }
        product.k_ids.split(',').forEach(((kid, kindex) => {
          let showIDList = []
          // 根据拼接好的vid过滤数据 
          // 过滤stock_map中的v1v2开头的v1v2v3 v1v2v4 成3 4 然后排序取出第一个
          let skuStock = stockKeys.filter(i => i.startsWith(skuID)).map(i => {
            return i.replace(skuID, '').match(/^v\d*/)[0].slice(1)
          })
          // 排序
          showIDList = Array.from(new Set(skuStock)).sort((a, b) => a - b)

          skuID += 'v' + (defaultVidsList.length ? defaultVidsList[kindex] : showIDList[0])
          skuList.push({
            id: kid,
            activeVid: (defaultVidsList.length ? defaultVidsList[kindex] : showIDList[0]),
            showIDList,
          })
        }))

        this.setData({
          product: product,
          sku: sku,
          img_url: product.img_url,
          price: product.price,
          skuList,
          stockKeys,
        })
      }
      console.log('watch productSkuData', this.data.productSkuData)
    },
    'productSkuData'(newVal, oldVal) {
      console.log(newVal)

    },
    'defaultNum'(newVal, oldVal) {
      this.setData({
        num: newVal
      })
    }
  },

  computed: {
    'productSkuName'(data) {
      if (data.skuList && data.skuList.length) {
        return data.skuList.map(i => data.sku.sku_kv_map['v' + i.activeVid]).join(' ')
      }
      return ''
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onClose(e) {
      console.log(e)
    },
    chooseVtype(event) {
      let dataset = event.currentTarget.dataset
      console.log(dataset)
      let activeVidList = this.data.skuList.map(i => i.activeVid)
      activeVidList[dataset.index] = dataset.vid
      let skuID = ''
      // 计算下面几级的展示并判断是否需要自动替换选项值
      activeVidList.forEach(((vid, vIndex) => {
        let changeAc = 'skuList[' + vIndex + '].activeVid'
        let changeList = 'skuList[' + vIndex + '].showIDList'
        if (vIndex <= dataset.index) {
          skuID += ('v' + vid)
          this.setData({
            [changeAc]: vid
          })
          return
        }
        let showIDList = []
        let skuStock = this.data.stockKeys.filter(i => i.startsWith(skuID)).map(i => {
          return i.replace(skuID, '').match(/^v\d*/)[0].slice(1)
        })
        showIDList = Array.from(new Set(skuStock)).sort((a, b) => a - b)
        let addId = showIDList.includes(vid) ? (vid) : showIDList[0]
        skuID += ('v' + addId)

        this.setData({
          [changeAc]: addId,
          [changeList]: showIDList
        })
      }))
    },

    confirmSku(event) {
      let sku_id = this.data.sku.sku_stock_map['v' + this.data.skuList.map(i => i.activeVid).join('v')].id
      this.triggerEvent('confirm', {
        num: this.data.num,
        sku_id
      })
    },
    changeNum(event) {
      this.setData({
        num: event.detail
      })
    },
    closeSku() {
      this.setData({
        show: false
      })
    }

  }
})